#include "InSdkTcpSystemClient.h"

#define DEF_TAG         "SdkTcpClient"

#define DEF_INNSDK_TCP_SYSTEM_TIMEOUT_SEC       (2 * 60)
#define DEF_INNSDK_TCP_SYSTEM_IP_ADDR           "127.0.0.1"

Com_s32 InSdkTcpSystem_CreatSocket(Com_void)
{
    Com_s32 addrlen;
    Com_s32 listen_socket;
    Com_s32 client_socket;
    struct sockaddr_in addr;

    memset(&addr, 0, sizeof(addr));

    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if(client_socket == -1)
    {
        perror("TcpClient: socket");
        return -1;
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(DEF_INNSDK_TCP_SYSTEM_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    inet_aton(DEF_INNSDK_TCP_SYSTEM_IP_ADDR, &(addr.sin_addr));

    addrlen = sizeof(addr);

    while (g_ComThread_Running)
    {
        listen_socket = connect(client_socket, (struct sockaddr *)&addr, addrlen);
        if (listen_socket == -1)
        {
            perror("TcpClient: connect");
            usleep(100 * 1000);
        }
        else
        {
            break;
        }
    }

    return client_socket;
}

Com_void Ext_InSdkTcpSystem_Cmd(Com_ps8 buff)
{
    Com_s32 ret;
    Com_s32 socket;
    fd_set fd;
    StSdkTcpSystemInfo info;
    StComSecondTimer timer;
    struct timeval timeout;

    memset(&info,0,sizeof(info));

    info.len = strlen(buff);
    memcpy(info.data,buff,info.len);
    socket = InSdkTcpSystem_CreatSocket();
    if(socket == -1)
    {
        goto exit;
    }

    send(socket,&info,info.len + 4,MSG_NOSIGNAL);
    Ext_InComTimer_GetSec(DEF_COM_SET_NEW_TIME,&timer);

    while(DEF_COM_TRUE)
    {
        FD_ZERO(&fd);
        FD_SET(socket,&fd);

        timeout.tv_sec = 2;
        timeout.tv_usec = 0;

        ret = select(socket + 1,&fd,NULL,NULL,&timeout);
        if(ret > 0)
        {
            if(FD_ISSET(socket,&fd))
            {
                Com_s8 buf[DEF_INNSDK_TCP_SYSTEM_SIZE];

                memset(buf,0,sizeof(buf));
                ret = recv(socket, buf,sizeof(buf),MSG_DONTWAIT);
                if(ret > 0)
                {
                    if(strcmp(buf,DEF_INNSDK_TCP_SYSTEM_HANDLE_OK) == 0)
                    {
                        PRT_DBG(DEF_TAG,"tcp handle ok\n");
                        break;
                    }
                }
            }
        }
        else if(ret == 0)
        {
            if (Ext_InComTimer_GetSec(DEF_COM_NOT_SET_TIME, &timer) >
                DEF_INNSDK_TCP_SYSTEM_TIMEOUT_SEC)
            {
                PRT_WARN(DEF_TAG,"tcp handle timeout\n");
                break;
            }
        }
        else
        {
            PRT_ERR(DEF_TAG,"select error\n");
            break;
        }
        usleep(10 * 1000);
    }

    close(socket);
exit:
    return;
}
